<template>
  <el-dialog
    v-loading.lock="loading"
    class="base-dialog system-user-dialog"
    :custom-class="'panna-dialog_big'"
    :append-to-body="true"
    :title="dataList.ReturnProcessing"
    align="center"
    :visible.sync="dialogFormVisible"
    @closed="cancel"
  >
    <div>
      <el-form
        :model="formData"
        :rules="formDataRules"
        status-icon
        label-width="140px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="dataList.DeviceBorrowType"
              :label-width="formLabelWidth"
              prop="type"
            >
              <span>{{ formData.typeName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="dataList.DeviceBorrower"
              :label-width="formLabelWidth"
              prop="borrowPersonName"
            >
              <span>{{ formData.borrowPersonName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="dataList.DeviceBorrowTime"
              :label-width="formLabelWidth"
              prop="borrowTime"
              :error="errorMsg.borrowTime"
            >
              <span>{{ formatTime(formData.borrowTime) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="dataList.DeviceBorrowReturnTime"
              :label-width="formLabelWidth"
              prop="returnDate"
              :error="errorMsg.returnDate"
            >
              <span>{{ formatTime(formData.returnDate) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="dataList.ReasonsOfBorrow"
              :label-width="formLabelWidth"
              prop="reason"
              :error="errorMsg.reason"
            >
              <span>{{ formData.reason }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="dataList.Deviceremark"
              :label-width="formLabelWidth"
              :error="errorMsg.remark"
            >
              <span>{{ formData.remark }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-divider class="el-divider-specail" content-position="left"
        ><span>{{ dataList.ReturnOfDevice }}</span>
      </el-divider>
      <el-table
        :data="formData.deviceBorrowInfoDtoList"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        >
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            {{ scope.row.num }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceSpecifications">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>

        <el-table-column :label="dataList.DeviceFactoryNum">
          <template slot-scope="scope">
            {{ scope.row.factoryNum }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DevicePersonResponsibleId">
          <template slot-scope="scope">
            {{ scope.row.personResponsibleName }}
          </template>
        </el-table-column>

        <el-table-column>
          <template #header>
            <span style="color: red">*</span>
            <span>{{ dataList.DeviceStorageAddress }}</span>
          </template>
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.storageAddress"
              :placeholder="dataList.DeviceStorageAddress"
            />
          </template>
        </el-table-column>

        <el-table-column>
          <template #header>
            <span style="color: red">*</span>
            <span>{{ dataList.ReturnOfDeviceStatus }}</span>
          </template>
          <template slot-scope="scope">
            <DicDropDownList
              v-model="scope.row.returnStatus"
              :dict-code="'deviceStatusList'"
              :display-text="displayText"
            />
          </template>
        </el-table-column>

        <el-table-column :label="dataList.Deviceremark">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              :placeholder="dataList.Deviceremark"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-divider class="el-divider-specail" content-position="left"
        ><span>{{ dataList.EquipmentAndSparepartsList }}</span>
      </el-divider>
      <el-table
        :data="formData.deviceParts"
        border
        style="width: 100%"
        height="400px"
      >
        <el-table-column align="center" :label="dataList.Number" width="100">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="deviceNum"
          :label="dataList.DeviceNumber"
        />
        <el-table-column
          align="center"
          prop="deviceName"
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        />
        <el-table-column align="center" prop="name" :label="dataList.Name" />
        <el-table-column
          align="center"
          prop="unit"
          :label="dataList.UnitOfMeasurement"
        />
        <el-table-column
          align="center"
          prop="loanCount"
          :label="dataList.BorrowQuantity"
        />
        <el-table-column align="center">
          <template #header>
            <span style="color: red">*</span>
            <span>{{ dataList.ReturnQuantity }}</span>
          </template>
          <template slot-scope="scope">
            <!-- @blur="handleInputBlur(scope.row)" -->
            <el-input
              v-model="scope.row.returnCount"
              autocomplete="off"
              :validate-event="false"
            ></el-input
          ></template>
        </el-table-column>
        <el-table-column align="center" :label="dataList.Deviceremark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" autocomplete="off"></el-input
          ></template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer" class="dialog-footer" align="center">
      <el-button
        type="primary"
        style="width: 100px"
        @click="onSubmit('formData')"
        >{{ btn.Confirm }}</el-button
      >
      <el-button @click="cancel">{{ btn.Cancel }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DicDropDownList from "../../components/DicDropDownList.vue";
import { get, borrowSendBackUpdate } from "../../api/DeviceBorrow.js";
import { GetListNoPage } from "../../api/DevicePartsLoan";
import { normal } from "../../utils/const";
import { formatTime } from "../../utils/time";
export default {
  name: "DeviceBorrowSendBackDialog",
  components: { DicDropDownList },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      displayText: [
        this.$t("ModuleDevice.Device.Normal"),
        this.$t("ModuleDevice.Device.Fault"),
        this.$t("ModuleDevice.Device.Downgrading"),
      ],
      loading: false,
      formLabelWidth: "100px",
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      initData: {
        id: 0,
        num: "",
        type: 0,
        typeName: "",
        statusId: 0,
        statusName: "",
        reason: "",
        returnDate: null,
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      formData: {
        borrowTime: null,
        id: 0,
        num: "",
        type: 0,
        typeName: "",
        statusId: 0,
        statusName: "",
        reason: "",
        returnDate: null,
        borrowPersonId: this.$store.getters.currentUserId,
        borrowPersonName: "",
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      returnDateOptions: {
        // 限制日期
        disabledDate: (time) => {
          return time.getTime() < new Date(this.formData.borrowTime).getTime();
        },
      },
      pickerOptions: {
        // 限制日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        },
      },
      formDataRules: {
        borrowTime: [
          {
            required: true,
            message: this.$t("ModuleDevice.Message.EntryIntoForceTime"),
            trigger: "change",
          },
          // { validator: validateDate, trigger: "change" },
        ],
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        type: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        typeName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        statusId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        statusName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        reason: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        borrowPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        borrowPersonName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        creatorId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        creatorName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        returnDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        type: "",
        typeName: "",
        statusId: "",
        statusName: "",
        reason: "",
        returnDate: "",
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
      errorMsg: {
        num: "",
        type: "",
        typeName: "",
        statusId: "",
        statusName: "",
        reason: "",
        returnDate: "",
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  created() {
    this.get();
  },
  methods: {
    formatTime,
    handleInputBlur(row) {
      // 正则表达式：必须为正整数
      const reg = /^[1-9]\d*$/;
      if (!reg.test(row.returnCount)) {
        this.$message.error(this.$t("ModuleDevice.Message.RegPositiveinteger"));
        row.returnCount = 1; // 重置为默认值
      }
    },
    cancel() {
      this.$emit("update:dialogFormVisible", false);
    },
    get() {
      get({ id: this.id })
        .then((res) => {
          this.formData = res.data;
          if (
            res.data.deviceBorrowInfoDtoList !== undefined &&
            res.data.deviceBorrowInfoDtoList !== null &&
            res.data.deviceBorrowInfoDtoList.length !== 0
          ) {
            var deviceBorrowInfoIdList = res.data.deviceBorrowInfoDtoList.map(
              (x) => x.deviceBorrowInfoId
            );
            GetListNoPage({
              deviceBorrowInfoIdList: deviceBorrowInfoIdList,
            }).then((res) => {
              this.formData.deviceParts = res.data;
              for (let i = 0; i < this.formData.deviceParts.length; i++) {
                this.formData.deviceParts[i].returnCount =
                  this.formData.deviceParts[i].loanCount;
              }
              const idMap = new Map();
              this.formData.deviceBorrowInfoDtoList.forEach((item, index) => {
                idMap.set(item.id, index);
              });
              this.formData.deviceParts.sort((a, b) => {
                return idMap.get(a.deviceId) - idMap.get(b.deviceId);
              });
            });
          }
          this.formData.deviceBorrowInfoDtoList =
            this.formData.deviceBorrowInfoDtoList.filter((item) => {
              return item.borrowStatus === 1;
            });
          this.formData.deviceBorrowInfoDtoList.map((item) => {
            item.returnStatus = normal;
          });
          // normal
        })
        .catch((res) => {});
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      this.formData.deviceSenBackList = [];
      var state = 0;
      var flag = true;
      this.formData.deviceParts.forEach((row) => {
        const reg = /^[0-9]\d*$/;
        if (!reg.test(row.returnCount)) {
          this.$message.error(
            this.$t("ModuleDevice.Message.RegPositiveinteger")
          );
          // row.returnCount = 1; // 重置为默认值
          flag = false;
          return false;
        }
      });
      if (!flag) {
        return false;
      }

      this.formData.deviceBorrowInfoDtoList.map((item) => {
        if (Number(item.returnStatus) === -1) {
          this.$message.warning(
            this.$t("ModuleDevice.Message.SelectReturnStatus")
          );
          state = 1;
          return false;
        }
        if (!item.storageAddress) {
          this.$message.warning(
            this.$t("ModuleDevice.Message.DeviceStorageAddressNotNull")
          );
          state = 1;
          return false;
        }
        var obj = {};
        obj.borrowId = item.borrowId;
        obj.deviceId = item.deviceId;
        obj.returnStatus = item.returnStatus;
        obj.returnAddress = item.storageAddress;
        obj.remark = item.remark;
        this.formData.deviceSenBackList.push(obj);
      });
      if (Number(state) === 0) {
        borrowSendBackUpdate(this.formData)
          .then((res) => {
            this.closeDialog();
          })
          .catch((res) => {});
      }
    },
  },
};
</script>
